package com.wstuo.common.tools.service;

import com.wstuo.common.tools.dao.IEmailServerDAO;
import com.wstuo.common.tools.dto.EmailServerDTO;
import com.wstuo.common.tools.entity.EmailServer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/***
 * ServicesEmail Service class.
 * 
 * @author QXY
 */
public class EmailServerService implements IEmailServerService {
	@Autowired
	private IEmailServerDAO emailServerDAO;

	/**
	 * 获取邮件服务器配置信息
	 * 
	 * @return EmailServerDTO
	 * */
	public EmailServerDTO findEmail() {
		List<EmailServer> entities = emailServerDAO.findAll();
		EmailServerDTO dto = new EmailServerDTO();
		if (entities != null && !entities.isEmpty()) {
			EmailServer es = entities.get(0);
			if (es.getEmailType() != null && es.getEmailType().equals("normal")||es.getEmailType().equals("exchange")) {//receive
				EmailServerDTO.entity2dto(es, dto);
			}else{
				if (entities.size()==2) {
					EmailServerDTO.entity2dto(entities.get(1), dto);
				}
			}
			
		}
		return dto;
	}
	
	@Override
	public EmailServerDTO findReceiveEmail() {
		List<EmailServer> entities = emailServerDAO.findAll();
		EmailServerDTO dto = new EmailServerDTO();
		if (entities != null && !entities.isEmpty()) {
			EmailServer es = entities.get(0);
			if (es.getEmailType() != null && 
					es.getEmailType().indexOf("eceive") > 0 ) {//receive
				EmailServerDTO.entity2dto(es, dto);
			}else{
				if (entities.size()==2) {
					EmailServerDTO.entity2dto(entities.get(1), dto);
				}
			}
		}
		return dto;
	}
	/**
	 * preservation Email server
	 * 
	 * @param emailServerDTO
	 * */
	@Transactional
	public void saveOrUpdateEmailServer(EmailServerDTO emailServerDTO) {
		if(emailServerDTO==null){
			emailServerDTO = new EmailServerDTO();
		}
		EmailServer es = null;
		if (emailServerDTO!=null&&emailServerDTO.getEmailServerId()!=null){
			es = emailServerDAO.findById(emailServerDTO.getEmailServerId());
		}
		if (es == null) {
			es = new EmailServer();
		}
		EmailServerDTO.dto2entity(emailServerDTO, es);
		emailServerDAO.merge(es);
		emailServerDTO.setEmailServerId(es.getEmailServerId());
	}


}
